package com.yonyou.brigade.cron.util;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.model.Developer;
import com.yonyou.brigade.basic_init.service.IDeveloperService;
import com.yonyou.ybzboot.starter.mail.model.Email;
import com.yonyou.ybzboot.starter.mail.service.IMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author houyb
 */
@Component
public class SendMailUtil {

    private static final Logger logger = LoggerFactory.getLogger(SendMailUtil.class);


    @Autowired
    @Qualifier("developerServiceImpl")
    private IDeveloperService developerService;

    @Autowired
    private IMailService mailService;

    @Value("${brigade.cur}")
    private String curEnv;

    /**
     * 给开发人员发送异常提示邮件
     * @param subject 邮件主题
     * @param errorMsg 邮件内容（异常信息）
     */
    public void sendMailToDeveloper(String subject, String errorMsg){
        Wrapper<Developer> developerWrapper = new EntityWrapper<>();
        developerWrapper.where("type={0}", "KF");
        List<Developer> developers = developerService.selectList(developerWrapper);
        String developerEmails = "";
        for (int j = 0; j < developers.size(); j++) {
            developerEmails += developers.get(j).getEmail();
            if (j < developers.size() - 1) {
                developerEmails += ",";
            }
        }
        Email email = new Email();
        String[] emails = developerEmails.split(",");
        email.setEmail(emails);
        email.setSubject(curEnv + subject);
        email.setContent(errorMsg);
        try {
            logger.error(errorMsg);
            mailService.send(email);
        } catch (Exception e1) {
            logger.error("提示" + curEnv + subject + "的邮件发送失败！" + e1.getMessage());
        }
    }
}
